﻿using BlazorAutoEx.Models;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Options;

namespace BlazorAutoEx.Services
{
    public class TimedWritingService : BackgroundService
    {

        private readonly IWebHostEnvironment _env;
        private DateTime _lastRunDate = DateTime.Now;

        public TimedWritingService(IWebHostEnvironment env)
        {
            _env = env;
        }

        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {

            while (!stoppingToken.IsCancellationRequested)
            {

                if (Program.isRun)
                {
                    await WriteToFileAsync();
                    _lastRunDate = DateTime.Now;
                }

                await Task.Delay(TimeSpan.FromSeconds(Program.timeSpan), stoppingToken); // 用设置里的时间间隔
            }
        }


        private async Task WriteToFileAsync()
        {
            string message = "未执行扣款";
            var timeSerCon = Dbcon.db.Queryable<TimedSerCfgdb>().First();
            if (timeSerCon.ExecuteSet == 2)
            {
                timeSerCon.ExTimeSec = timeSerCon.ExeTime / (double)TimeSpan.TicksPerSecond;
                Program.timeSpan = timeSerCon.ExTimeSec ?? 28800;
                Program.lastTime = DateTime.Now;
                Program.nextTime = DateTime.Now.AddSeconds(Program.timeSpan);
                timeSerCon.LastTime = Program.lastTime;
                timeSerCon.NextTime = Program.nextTime;
                Dbcon.db.Updateable(timeSerCon).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommand();

                await exe.模拟程序执行();

                message = $"这是间隔{Program.timeSpan}秒执行一次";

            }
            if (timeSerCon.ExecuteSet == 3)
            {
                DateTime now = DateTime.Now;
                var timeList = Dbcon.db.Queryable<TimeAutoSet>().ToList().OrderBy(it => it.ExeTime);
                var time = timeList
                    .Select(it => (TimeSpan?)it.ExeTimeOnly.ToTimeSpan())
                    .FirstOrDefault(it => it > now.TimeOfDay, null);
                if (time is not null)
                {
                    //算出时间差
                    DateTime newDateWithMidnight = now.Date + time.Value;
                    timeSerCon.ExTimeSec = (newDateWithMidnight - now).TotalSeconds;
                    message = $"这是当天定时执行，距离下次还有{timeSerCon.ExTimeSec}秒";
                }
                else if (timeList.Any())
                {
                    //算出明天第一个时间与现在之间的时间差
                    DateTime newDateWithMidnight = now.Date.AddDays(1) + (timeList.First()?.ExeTimeOnly.ToTimeSpan() ?? TimeSpan.Zero);
                    timeSerCon.ExTimeSec = (newDateWithMidnight - now).TotalSeconds;
                    message = $"这是明天定时执行，距离下次还有{timeSerCon.ExTimeSec}秒";
                }

                Program.timeSpan = timeSerCon.ExTimeSec ?? 28800;
                Program.lastTime = now;
                Program.nextTime = now.AddSeconds(Program.timeSpan);
                timeSerCon.LastTime = Program.lastTime;
                timeSerCon.NextTime = Program.nextTime;
                Dbcon.db.Updateable(timeSerCon).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommand();

                await exe.模拟程序执行();


            }


            //数据库里插入一条当前时间
            var ddd = Dbcon.db.Insertable(new TimedSerText() { RunTime = DateTime.Now }).IgnoreColumns(ignoreNullColumn: true).ExecuteReturnEntity();

            //写入文件
            var content = $"{ddd.ID},{DateTime.Now}: {message}";
            var filePath = Path.Combine(_env.ContentRootPath, "logger.txt");

            await File.AppendAllLinesAsync(filePath, new[] { content });
        }
    }


}
